package com.lp.security.schedule;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lp.biz.content.mapper.BizContentScheduleMapper;
import com.lp.biz.content.mapper.BizCoreContentMapper;
import com.lp.biz.content.mapper.BizCourseChapterMapper;
import com.lp.biz.content.model.entity.BizContentSchedule;
import com.lp.biz.content.model.entity.BizCoreContent;
import com.lp.biz.content.model.entity.BizCourseChapter;
import com.lp.biz.operations.mapper.BizRecommendDailyMapper;
import com.lp.biz.operations.model.entity.BizRecommendDaily;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

import static com.lp.common.constant.CategoryConstant.*;
import static com.lp.common.constant.CommonConstant.NEGATE;
import static com.lp.common.constant.CommonConstant.SURE;
import static com.lp.common.constant.HomeConstant.CODE_DAILY;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-06-03 20:32:33
 */
@Slf4j
@Component
public class ContentSchedule {

    @Autowired
    private BizRecommendDailyMapper dailyMapper;

    @Autowired
    private BizCoreContentMapper contentMapper;

    @Autowired
    private BizCourseChapterMapper chapterMapper;

    @Autowired
    private BizContentScheduleMapper scheduleMapper;

    @Scheduled(cron = "0 */10 * * * ?")
    @Transactional(rollbackFor = RuntimeException.class)
    public void contentDisplay() {
        log.info("自动上架：开始处理自动上架");
        LocalDateTime now = LocalDateTime.now();
        for (BizContentSchedule schedule : scheduleMapper.selectList(new QueryWrapper<BizContentSchedule>().lambda()
                .eq(BizContentSchedule::getStatus, NEGATE).le(BizContentSchedule::getStartAt, now))) {
            switch (schedule.getCode()) {
                case CODE_READING:
                    contentReadingHandler(schedule);
                    break;
                case CODE_DAILY:
                    contentDailyHandler(schedule);
                    break;
                case CODE_COURSE:
                    contentCourseHandler(schedule);
                    break;
                default:
                    break;
            }
        }
        log.info("自动上架：定时上架结束");
    }

    private void contentReadingHandler(BizContentSchedule schedule) {
        log.info("自动上架：处理共读会自动上架，id：{}", schedule.getContentId());
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 根据内容ID查询业务内容信息
        BizCoreContent content = contentMapper.selectById(schedule.getContentId());

        // 如果内容的显示类型不为时间类型，或者内容已被标记为删除，则删除该调度
        if (!content.getDisplayType().equals(DISPLAY_TYPE_TIME) || content.getIsDeleted().equals(SURE)) {
            scheduleMapper.deleteById(schedule.getId());
        } else if (content.getIsDisplay() == null || content.getDisplayAt() == null || content.getIsDisplay().equals(NEGATE)) {
            // 如果内容未设置显示状态或显示状态为否，则将内容设置为显示，并记录显示时间
            content.setIsDisplay(SURE);
            content.setDisplayAt(now);
            contentMapper.updateById(content);
            // 更新调度状态为已发布
            schedule.setStatus(SURE);
            scheduleMapper.updateById(schedule);
        } else {
            // 如果内容已设置为显示，但还未到显示时间，则更新调度状态为已发布
            schedule.setStatus(SURE);
            scheduleMapper.updateById(schedule);
            // 如果内容未设置显示时间，或显示时间在当前时间之后，则立即更新内容的显示时间为当前时间
            if (content.getDisplayAt() == null || content.getDisplayAt().isAfter(now)) {
                content.setDisplayAt(now);
                contentMapper.updateById(content);
            }
        }
    }

    private void contentDailyHandler(BizContentSchedule schedule) {
        log.info("自动上架：处理每日故事自动上架，id：{}", schedule.getContentId());
        LocalDateTime now = LocalDateTime.now();
        BizRecommendDaily daily = dailyMapper.selectById(schedule.getContentId());
        if (!daily.getDisplayType().equals(DISPLAY_TYPE_TIME) || daily.getIsDeleted().equals(SURE)) {
            scheduleMapper.deleteById(schedule.getId());
        } else if (daily.getIsDisplay() == null || daily.getDisplayAt() == null || daily.getIsDisplay().equals(NEGATE)) {
            schedule.setStatus(SURE);
            scheduleMapper.updateById(schedule);
            daily.setIsDisplay(SURE);
            daily.setDisplayAt(now);
            dailyMapper.updateById(daily);
        } else {
            schedule.setStatus(SURE);
            scheduleMapper.updateById(schedule);
            if (daily.getDisplayAt() == null || daily.getDisplayAt().isAfter(now)) {
                daily.setDisplayAt(now);
                dailyMapper.updateById(daily);
            }
        }
    }

    private void contentCourseHandler(BizContentSchedule schedule) {
        log.info("自动上架：处理课程章节自动上架，id：{}", schedule.getContentId());
        BizCourseChapter chapter = chapterMapper.selectById(schedule.getContentId());
        if (!chapter.getDisplayType().equals(DISPLAY_TYPE_TIME) || chapter.getIsDeleted().equals(SURE)) {
            scheduleMapper.deleteById(schedule.getId());
        } else if (!chapter.getIsDisplay().equals(SURE)) {
            schedule.setStatus(SURE);
            chapter.setIsDisplay(SURE);
            chapter.setDisplayAt(schedule.getStartAt());
            scheduleMapper.updateById(schedule);
            chapterMapper.updateById(chapter);
        } else {
            schedule.setStatus(SURE);
            scheduleMapper.updateById(schedule);
        }
    }

}
